package org.test.doc;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import com.lowagie.text.Cell;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.PdfWriter;

public class HtmlToWord {

	public static void main(String[] args) {
		// 创建文件
		File f = new File("D:/buffer/");
		f.mkdirs();
		f = new File(f.getPath() + "/demo.pdf");
		// 创建itext文档对象
		Document document = new Document(PageSize.A4);
		try {
			// 创建RtfWriter对象
			PdfWriter.getInstance(document, new FileOutputStream(f));
			document.open();
			// 添加html代码
			String html = "<h1>htmlcontent</h1>" + "<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\">"
					+ "<thead>" + "<tr>" + "<th>第一列</th>" + "<th>第二列</th>" + "</tr>" + "</thead>" + "<tbody>" + "<tr>"
					+ "<td>cell11</td>" + "<td>cell21</td>" + "</tr>" + "</tbody>" + "</table>";
			addHtmlContent(document, html, "D:/", 500);
		} catch (Exception e) {
			System.err.println(e.getMessage());
		} finally {
			if (document != null) {
				document.close();
			}
		}

	}

	
	public static void addHtmlContent(Object element, String html, String root, float imgWidth)
			throws IOException, DocumentException {
		StyleSheet ss = new StyleSheet();
		html = html.replace("..", root);
		List<?> htmlList = HTMLWorker.parseToList(new StringReader(html), ss);
		for (int i = 0; i < htmlList.size(); i++) {
			Element e = (Element) htmlList.get(i);
			for (Object object : e.getChunks()) {
				if (object instanceof Chunk) {
					Chunk ch = (Chunk) object;
					if (ch.getImage() != null) {
						float width = imgWidth;
						float height = ch.getImage().getHeight() / ch.getImage().getWidth() * width;
						ch.getImage().scaleAbsolute(width, height);
					}
				}
			}
			if (element instanceof Cell) {
				((Cell) element).add(e);
			}
			if (element instanceof Paragraph) {
				((Paragraph) element).add(e);
			}
			if (element instanceof Document) {
				((Document) element).add(e);
			}
		}
	}

}
